/**
 * 表单验证工具函数
 */

/**
 * 验证手机号
 * @param phone 手机号
 * @returns 是否有效
 */
export function isValidPhone(phone: string): boolean {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(phone)
}

/**
 * 验证邮箱
 * @param email 邮箱
 * @returns 是否有效
 */
export function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

/**
 * 验证身份证号
 * @param idCard 身份证号
 * @returns 是否有效
 */
export function isValidIdCard(idCard: string): boolean {
  const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
  return idCardRegex.test(idCard)
}

/**
 * 验证密码强度
 * @param password 密码
 * @returns 强度等级 (0-3)
 */
export function getPasswordStrength(password: string): number {
  if (password.length < 6) return 0

  let strength = 0

  // 包含小写字母
  if (/[a-z]/.test(password)) strength++

  // 包含大写字母
  if (/[A-Z]/.test(password)) strength++

  // 包含数字
  if (/\d/.test(password)) strength++

  // 包含特殊字符
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++

  // 长度加分
  if (password.length >= 8) strength = Math.min(strength + 1, 4)
  if (password.length >= 12) strength = Math.min(strength + 1, 4)

  return Math.min(strength, 3)
}

/**
 * 验证URL
 * @param url URL地址
 * @returns 是否有效
 */
export function isValidUrl(url: string): boolean {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

/**
 * 验证IP地址
 * @param ip IP地址
 * @returns 是否有效
 */
export function isValidIP(ip: string): boolean {
  const ipRegex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  return ipRegex.test(ip)
}

/**
 * 验证端口号
 * @param port 端口号
 * @returns 是否有效
 */
export function isValidPort(port: number | string): boolean {
  const portNum = typeof port === 'string' ? parseInt(port, 10) : port
  return Number.isInteger(portNum) && portNum >= 1 && portNum <= 65535
}

/**
 * Element Plus 表单验证规则生成器
 */
export const createRules = {
  /**
   * 必填规则
   */
  required: (message: string = '此字段为必填项') => ({
    required: true,
    message,
    trigger: ['blur', 'change'],
  }),

  /**
   * 手机号验证规则
   */
  phone: (required: boolean = true) => {
    const rules: any[] = []

    if (required) {
      rules.push({
        required: true,
        message: '请输入手机号',
        trigger: ['blur', 'change'],
      })
    }

    rules.push({
      validator: (_: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }

        if (!isValidPhone(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change'],
    })

    return rules
  },

  /**
   * 邮箱验证规则
   */
  email: (required: boolean = true) => {
    const rules: any[] = []

    if (required) {
      rules.push({
        required: true,
        message: '请输入邮箱地址',
        trigger: ['blur', 'change'],
      })
    }

    rules.push({
      validator: (_: any, value: string, callback: Function) => {
        if (!value) {
          callback()
          return
        }

        if (!isValidEmail(value)) {
          callback(new Error('请输入正确的邮箱地址'))
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change'],
    })

    return rules
  },

  /**
   * 密码验证规则
   */
  password: (minLength: number = 6, requireStrong: boolean = false) => {
    return [
      {
        required: true,
        message: '请输入密码',
        trigger: ['blur', 'change'],
      },
      {
        min: minLength,
        message: `密码长度不能少于${minLength}位`,
        trigger: ['blur', 'change'],
      },
      ...(requireStrong
        ? [
            {
              validator: (_: any, value: string, callback: Function) => {
                if (!value) {
                  callback()
                  return
                }

                const strength = getPasswordStrength(value)
                if (strength < 2) {
                  callback(new Error('密码强度太弱，请包含字母、数字或特殊字符'))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change'],
            },
          ]
        : []),
    ]
  },

  /**
   * 确认密码验证规则
   */
  confirmPassword: (passwordField: string = 'password') => {
    return [
      {
        required: true,
        message: '请再次输入密码',
        trigger: ['blur', 'change'],
      },
      {
        validator: (_: any, value: string, callback: Function) => {
          const form = _.form || {}
          if (value !== form[passwordField]) {
            callback(new Error('两次密码输入不一致'))
          } else {
            callback()
          }
        },
        trigger: ['blur', 'change'],
      },
    ]
  },

  /**
   * 数字范围验证规则
   */
  numberRange: (min?: number, max?: number, required: boolean = true) => {
    const rules: any[] = []

    if (required) {
      rules.push({
        required: true,
        message: '请输入数字',
        trigger: ['blur', 'change'],
      })
    }

    if (min !== undefined || max !== undefined) {
      rules.push({
        type: 'number',
        min,
        max,
        message: `请输入${min !== undefined ? min + '到' : '小于等于'}${max !== undefined ? max : ''}的数字`,
        trigger: ['blur', 'change'],
      })
    }

    return rules
  },
}
